/*
 * Copyright 2018-2021 guerlab.net and other contributors.
 *
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.guerlab.smart.pay.service.service.impl;

import net.guerlab.commons.number.NumberHelper;
import net.guerlab.smart.pay.core.exception.*;
import net.guerlab.smart.pay.core.searchparams.PayLogNotifySearchParams;
import net.guerlab.smart.pay.service.entity.PayLogNotify;
import net.guerlab.smart.pay.service.mapper.PayLogNotifyMapper;
import net.guerlab.smart.pay.service.service.PayLogNotifyService;
import net.guerlab.smart.platform.server.service.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 支付记录通知服务实现
 *
 * @author guer
 */
@Service
public class PayLogNotifyServiceImpl extends BaseServiceImpl<PayLogNotify, Long, PayLogNotifyMapper, PayLogNotifySearchParams>
        implements PayLogNotifyService {

    @Override
    public void markException(Long id, String exceptionReason) {
        exceptionReason = StringUtils.trimToNull(exceptionReason);
        if (NumberHelper.greaterZero(id) && exceptionReason != null) {
            getBaseMapper().markException(id, exceptionReason);
        }
    }

    @Override
    public void removeExceptionMark(Long id) {
        getBaseMapper().removeExceptionMark(id);
    }

    @Override
    protected void insertBefore(PayLogNotify entity) {
        String payChannel = StringUtils.trimToNull(entity.getPayChannel());
        String outOrderSn = StringUtils.trimToNull(entity.getOutOrderSn());

        if (!NumberHelper.greaterOrEqualZero(entity.getPayLogId())) {
            throw new PayLogIdInvalidException();
        }
        if (!NumberHelper.greaterOrEqualZero(entity.getPayOrderId())) {
            throw new PayOrderIdInvalidException();
        }
        if (payChannel == null) {
            throw new PayChannelInvalidException();
        }
        if (!NumberHelper.greaterOrEqualZero(entity.getAmount())) {
            throw new PayAmountInvalidException();
        }
        if (outOrderSn == null) {
            throw new OutOrderSnInvalidException();
        }

        entity.setPayLogNotifyId(sequence.nextId());
        entity.setCreateTime(LocalDateTime.now());
        entity.setPayChannel(payChannel);
        entity.setOutOrderSn(outOrderSn);
        entity.setExceptionFlag(false);
        entity.setExceptionReason(null);
    }
}
